import os
import conf
from incl import *
from CMS import *
from data_objects import *
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class NewRecipesPage(webapp.RequestHandler):
  def get(self):
    a = Admin()
    a.checkUserRights(self)
    
    t_val = {
      'is_user_admin': users.is_current_user_admin(),
      'config': conf,
    }

    a.cms.showForm(self, 'new_recipe_form.html', t_val)  
    
class EditRecipePage(webapp.RequestHandler):
  def post(self):
    a = Admin()
    a.checkUserRights(self)
    
    key = db.Key(self.request.get('key'))
    recipe = Recipes.all().filter("__key__ =", key).get()
    if recipe:
      t_val = {
        'r': recipe,
        'actionURL': a.Recipe.saveUrl(),
        'is_user_admin': users.is_current_user_admin(),
        'config': conf,
      }
      a.cms.showForm(self, 'edit_recipe_form.html', t_val)
    else:
      a.cms.msgError(self, "Can't find recipe by key.");

class SaveRecipe(webapp.RequestHandler):
  def post(self):
    a = Admin()
    a.checkUserRights(self)
    
    r_key = self.request.get('key')
    if r_key:
      r_key = db.Key(r_key)
      recipe = Recipes.all().filter("__key__ =", r_key).get()
    else:
      recipe = Recipes(author=users.get_current_user(), 
                     name = "nobody")
    if recipe:
      if users.get_current_user():
        recipe.author = users.get_current_user()
    
      recipe.name = self.request.get('name')
      recipe.descript = self.request.get('descript')
      recipe.put()
    
    self.redirect(a.Recipe.ListUrl())

class DelRecipe(webapp.RequestHandler):
  def post(self):
    a = Admin()
    a.checkUserRights(self)
    r_key = self.request.get('key')

    if not r_key: 
      a.cms.msgError(self, "Unknown error!")
    else:
      r_key = db.Key(r_key)

    recipe = Recipes.all().filter("__key__ =", r_key).get()
    if recipe:
      recipe.is_deleted = not recipe.is_deleted
      recipe.put()

    self.redirect(a.Recipe.ListUrl())

class ChangeRecipe(webapp.RequestHandler):
  def post(self):
    a = Admin()
    a.checkUserRights(self)
	

    r_key = self.request.get('key')
    self.response.out.write(r_key+'<br/>')
    if r_key:
      recipe = Recipes.get(r_key)
      self.response.out.write(recipe.key())
      if recipe is not None:
        args = self.request.arguments()
        for arg in args:
          if arg not in ['key', 'submit']:
            self.response.out.write(arg + '<br/>')
            setattr(recipe, arg, self.request.get(arg) in ['true', 'True'])
      recipe.put()
    self.redirect('/admin/recipes/list')

class RecipesListPage(webapp.RequestHandler):
  def get(self):
    
    fromItem = int(self.request.get('from', default_value='0'))
    itemsCount = 10
    
    a = Admin()
    a.checkUserRights(self)
    
    recipes = Recipes.all().order("-pub_date").fetch(limit=itemsCount, offset=fromItem)
    list_len = Recipes.all().count() 
    t_val = {
      'recipes': recipes,
      'list_len': list_len,
      'back_pos': fromItem - 10 if fromItem - 10 > 0 else 0,
      'next_pos': fromItem + 10 if fromItem + 10 < list_len else fromItem,
      'formName': 'Recipes List',
      'is_user_admin': users.is_current_user_admin(),
      'config': conf,
    }

    a.cms.showForm(self, 'recipes_list_form.html', t_val)
        
class UserList(webapp.RequestHandler):
  def get(self):
    a = Admin()
    a.checkUserRights(self)

    q = UserProfiles.all()
    results = q.fetch(50)
    template_values = {
      'users': results,
      'is_user_admin': users.is_current_user_admin(),
      'formName': 'users list',
      'config': conf,
    }
    path = os.path.join(os.path.dirname(__file__), 'user-list.html')
    self.response.out.write(template.render(path, template_values))

class DelUser(webapp.RequestHandler):
  def get(self):
    a = Admin()
    a.checkUserRights(self)

    user = UserProfiles.get(self.request.get('id'))
    if user is not None:
      user.is_deleted = not user.is_deleted
      user.put()
    self.redirect(Admin.User.ListUrl())

class EditUser(webapp.RequestHandler):
  def get(self):
    a = Admin()
    a.checkUserRights(self)
    
    user = UserProfiles.get(self.request.get('id'))
    if user is not None:
      t_val = {
        'user': user,
        'is_user_admin': users.is_current_user_admin(),
        'formName': 'Edit User',
        'actionURL': a.User.saveUrl(),
        'config': conf,
      }
      a.cms.showForm(self, 'fmUserEdit.html', t_val)
    else:
      a.cms.msgError(self, 'Error')

  def post(self):
    a = Admin()
    a.checkUserRights(self)

    user = UserProfiles.get(self.request.get('id'))
    if user is not None:
      user.name = self.request.get('name')
      user.midname = self.request.get('midname')
      user.surname = self.request.get('surname')
      user.gender = self.request.get('gender')
      user.city = self.request.get('city')

      user.put()

    self.redirect(Admin.User.ListUrl());

class UserClass:
  usrData = {
    'List':     ('/admin/user/list',     UserList),
    'Delete':   ('/admin/user/delete',   DelUser),
    'Undelete': ('/admin/user/undelete', DelUser),
    'Edit':     ('/admin/user/edit',     EditUser),
    'Save':     ('/admin/user/save',     EditUser),
  }

  def ListUrl(self):
    return self.usrData['List'][0]
  
  def saveUrl(self):
    return self.usrData['Save'][0]

  def getWebAppList(self):
    return self.usrData.values()

class RecipesClass:
  rcpData = {
    'List':   ('/admin/recipes/list',   RecipesListPage),
    'Add':    ('/admin/recipes/add',    NewRecipesPage),
    'Save':   ('/admin/recipes/save',   SaveRecipe),
    'Edit':   ('/admin/recipes/edit',   EditRecipePage),
    'Delete': ('/admin/recipes/delete', DelRecipe),
    'Change': ('/admin/recipes/change', ChangeRecipe),
  }

  def ListUrl(self):
    return self.rcpData['List'][0]
  
  def saveUrl(self):
    return self.rcpData['Save'][0]

  def getWebAppList(self):
    return self.rcpData.values()


class Admin:
  User = UserClass()
  Recipe = RecipesClass()
  cms = CMS()

  def checkUserRights(self, s):    
    if users.get_current_user():
      if not users.is_current_user_admin():
        s.redirect('/')
    else:
      s.redirect('/')

def main():
  application = webapp.WSGIApplication( 
    Admin.Recipe.getWebAppList() +
    Admin.User.getWebAppList(), debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
